package com.gouaixin.bee.beeframework2.activity;

import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.app.FragmentActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.TextView;

import com.ab.util.AbDialogUtil;
import com.ab.util.AbImageUtil;
import com.ab.util.AbToastUtil;
import com.google.gson.Gson;
import com.gouaixin.bee.beeframework2.R;
import com.gouaixin.bee.beeframework2.adapter.XiangceAdapter;
import com.gouaixin.bee.beeframework2.bean.USER;
import com.gouaixin.bee.beeframework2.tool.PreferencesUtils;
import com.gouaixin.bee.beeframework2.tool.mLog;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.BmobUser;
import cn.bmob.v3.datatype.BmobFile;
import cn.bmob.v3.listener.GetListener;
import cn.bmob.v3.listener.UpdateListener;
import cn.bmob.v3.listener.UploadFileListener;

/**
 * Created by Administrator on 2015/3/9.
 */

//我的相册
public class B7_xiangceActivity extends FragmentActivity {
    Context context = B7_xiangceActivity.this;

    //上传按钮
//    TextView textView;

    //内容区域
    GridView gridView;
    XiangceAdapter adapter = new XiangceAdapter(context);
    List<BmobFile> datas = new ArrayList<BmobFile>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.b7_xiangce);

        initHead();

        initContent();

        setListener();

        getMyData();
    }

    private void setListener() {
//        textView.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                showMyDialog();
//            }
//        });

//        textView.setVisibility(View.GONE);

        gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (position == 0) {
                    showMyDialog();
                } else {
//                    AbToastUtil.showToast(context,"你点击了："+position);
                    BmobFile micon = datas.get(position-1);
                    String url=micon.getFileUrl(context);
                    if(url!=null&&!url.equals("")){
                        mLog.e("跳转到showPhotoURLActivity：url="+url);
                        Intent it = new Intent(context, showPhotoURLActivity.class);
                        it.putExtra("url", url);
                        startActivity(it);
                    }
                }
            }
        });


    }


    /**
     * 选择照片或相册，上传
     */
    private void showMyDialog() {

        View mView = LayoutInflater.from(context).inflate(R.layout.dialog_xuanzetupian, null);
        AbDialogUtil.showDialog(mView);
//
        TextView lijiPaizhao = (TextView) mView.findViewById(R.id.lijipaizhao);
        TextView bendiXiangce = (TextView) mView.findViewById(R.id.bendixiangce);
        lijiPaizhao.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(
                        MediaStore.ACTION_IMAGE_CAPTURE);
                //下面这句指定调用相机拍照后的照片存储的路径
                file_path = new Date().getTime() + ".png";
                intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri
                        .fromFile(new File(Environment
                                .getExternalStorageDirectory(),
                                file_path
                        )));
                startActivityForResult(intent, 1);
                AbDialogUtil.removeDialog(context);
            }
        });
        bendiXiangce.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                Intent intent2 = new Intent();
                intent2.setType("image/*");
                intent2.setAction(Intent.ACTION_GET_CONTENT);
                startActivityForResult(intent2, 2);
                AbDialogUtil.removeDialog(context);
            }
        });


    }

    /**
     * 得到个人详情
     *
     * @return
     */
    private void getMyData() {
        BmobQuery<USER> query = new BmobQuery<USER>();
        query.getObject(context, BmobUser.getCurrentUser(context).getObjectId(), new GetListener<USER>() {
            @Override
            public void onSuccess(USER user) {
                setMyData(user);
            }

            @Override
            public void onFailure(int i, String s) {

            }
        });

    }

    private void setMyData(USER user) {
        mLog.e("setMyData:" + new Gson().toJson(user));

        datas = user.getXiangce();
//        datas = FangkeDao.query(context);
        if (datas == null) {
            datas = new ArrayList<BmobFile>();

        }

        adapter.setData(datas);
        adapter.notifyDataSetChanged();

    }

    /**
     * 内容区域的监听
     */
    private void initContent() {
//        textView= (TextView) findViewById(R.id.add);

        gridView = (GridView) findViewById(R.id.gridview);
        gridView.setAdapter(adapter);
        gridView.setSelector(new ColorDrawable(Color.TRANSPARENT));
    }


    /**
     * 头部的监听
     */
    private void initHead() {
        //顶部
        ImageView back;//返回
        TextView title;//标题

        back = (ImageView) findViewById(R.id.back);
        title = (TextView) findViewById(R.id.title);

        back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

    }

    String file_path;//图片路径
    String file_path2;//裁剪后的图片路径

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {

        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            // 如果是直接从相册获取
            case 2:
                if (data != null && data.getData() != null) {

                    mLog.e("直接从相册获取:返回非空");
                    startPhotoZoom(data.getData());


                } else {
                    mLog.e("直接从相册获取:返回为空");
                }


                break;
            // 如果是调用相机拍照时
            case 1:
                if (data != null && data.getData() != null) {
                    mLog.e("调用相机拍照时:返回非空");
                    File temp = new File(Environment.getExternalStorageDirectory()
                            + "/" + file_path);
                    if (Uri.fromFile(temp) != null) {
                        startPhotoZoom(Uri.fromFile(temp));
                    }
                } else {
                    mLog.e("调用相机拍照时:返回为空");
                }

                break;
            // 取得裁剪后的图片
            case 3:
                mLog.e("取得裁剪后的图片:返回");
                /**
                 * 非空判断大家一定要验证，如果不验证的话，
                 * 在剪裁之后如果发现不满意，要重新裁剪，丢弃
                 * 当前功能时，会报NullException，小马只
                 * 在这个地方加下，大家可以根据不同情况在合适的
                 * 地方做判断处理类似情况
                 *
                 */
                if (data != null) {
                    setPicToView(data);
                }
                break;
            default:
                break;

        }
    }

    private void uploadBitmap(final Bitmap bitmap) {
        mLog.e("进入上传图片的方法：");

        file_path2 = new Date().getTime() + ".png";

        if (saveBitmap2file(bitmap, file_path2)) {
            mLog.e("图片转文件成功：" + file_path2);

            final BmobFile file = new BmobFile(new File("/sdcard/" + file_path2));

//            mLog.e("文件转bomb成功：url=" + file.getFileUrl(context));

            file.upload(context, new UploadFileListener() {
                @Override
                public void onProgress(Integer integer) {
                }

                @Override
                public void onSuccess() {
                    mLog.e("文件上传成功：" + file_path2);
//
                    USER myuser = BmobUser.getCurrentUser(context, USER.class);

                    List<BmobFile> bmobFiles = myuser.getXiangce();
                    if (bmobFiles == null) {
                        bmobFiles = new ArrayList<BmobFile>();
                    }
                    bmobFiles.add(file);
                    myuser.setXiangce(bmobFiles);
                    myuser.update(context, new UpdateListener() {
                        @Override
                        public void onSuccess() {
                            AbToastUtil.showToast(context, "更新用户相册成功");
                            PreferencesUtils.putString(context, "icon", file.getFileUrl(context));
                            refreshXiangce();

                        }

                        @Override
                        public void onFailure(int i, String s) {
                            mLog.e("更新用户头像失败：" + s);
                        }
                    });

                }

                @Override
                public void onFailure(int i, String s) {
                    AbToastUtil.showToast(context, "网络故障，请稍后再试");
                    mLog.e("文件上传失败：" + s);
                }
            });


        } else {
            mLog.e("图片转文件失败：");
        }


    }

    /**
     * 刷新相册
     */
    private void refreshXiangce() {
        getMyData();
    }

    protected String getAbsoluteImagePath(Uri uri) {
        // can post image
        String[] proj = {MediaStore.Images.Media.DATA};
        Cursor cursor = managedQuery(uri,
                proj,                 // Which columns to return
                null,       // WHERE clause; which rows to return (all rows)
                null,       // WHERE clause selection arguments (none)
                null);                 // Order-by clause (ascending by jid)
        int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
        cursor.moveToFirst();
        return cursor.getString(column_index);
    }

    boolean saveBitmap2file(Bitmap bmp, String filename) {
        Bitmap.CompressFormat format = Bitmap.CompressFormat.JPEG;
        int quality = 100;
        OutputStream stream = null;
        try {
            stream = new FileOutputStream("/sdcard/" + filename);
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        if (stream != null) {
            return bmp.compress(format, quality, stream);
        } else {
            return false;
        }


    }

    /**
     * 裁剪图片方法实现
     *
     * @param uri
     */
    public void startPhotoZoom(Uri uri) {
        /*
         * 至于下面这个Intent的ACTION是怎么知道的，大家可以看下自己路径下的如下网页
         * yourself_sdk_path/docs/reference/android/content/Intent.html
         * 直接在里面Ctrl+F搜：CROP ，之前小马没仔细看过，其实安卓系统早已经有自带图片裁剪功能,
         * 是直接调本地库的，小马不懂C C++  这个不做详细了解去了，有轮子就用轮子，不再研究轮子是怎么
         * 制做的了...吼吼
         */
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        //下面这个crop=true是设置在开启的Intent中设置显示的VIEW可裁剪
        intent.putExtra("crop", "true");
        // aspectX aspectY 是宽高的比例
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        // outputX outputY 是裁剪图片宽高
        intent.putExtra("outputX", 150);
        intent.putExtra("outputY", 150);
        intent.putExtra("return-data", true);
        startActivityForResult(intent, 3);
    }

    /**
     * 保存裁剪之后的图片数据
     *
     * @param picdata
     */
    private void setPicToView(Intent picdata) {
        Bundle extras = picdata.getExtras();
        if (extras != null) {
            Bitmap photo = extras.getParcelable("data");

            mLog.e("显示裁剪后的图片：");


            uploadBitmap(photo);

        }
    }

    //显示可缩放图片
    public void show(View view) {
//        View mView = LayoutInflater.from(context).inflate(R.layout.dialog_photo, null);
//        AbDialogUtil.showDialog(mView);
//
//        DragImageView xphoto= (DragImageView) mView.findViewById(R.id.xphoto);

//        BitmapUtils bitmapUtils=new BitmapUtils(context);

        //View是你需要截图的View
        mLog.e("View是你需要截图的View");
        view.setDrawingCacheEnabled(true);
        view.buildDrawingCache();
        Bitmap bmp = view.getDrawingCache();
        view.setDrawingCacheEnabled(false);

        mLog.e("跳转到缩放界面");
        Intent it = new Intent(context, showPhotoActivity.class);
        it.putExtra("bitmap", bmp);
        startActivity(it);


    }


}
